// main.js - 修改后的版本
const { app, BrowserWindow, ipcMain, Menu } = require('electron');
const path = require('path');
const WebSocket = require('ws');
const fs = require('fs');
const { print } = require('pdf-to-printer');
const { exec } = require('child_process');
const { getDefaultPrinter } = require('pdf-to-printer');

let mainWindow;
let wsServer = null;
let isServiceRunning = false;

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            // 忽略证书错误
            webSecurity: false,
            allowRunningInsecureContent: true
        },
        icon: path.join(__dirname, 'assets/icon.png'),
        titleBarStyle: 'default'
    });

    Menu.setApplicationMenu(null);
    
    mainWindow.loadFile('index.html');
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        if (wsServer) {
            wsServer.close();
        }
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

// IPC 通信处理
ipcMain.handle('start-service', async () => {
    try {
        if (isServiceRunning) {
            return { success: false, message: '服务已在运行中' };
        }

        wsServer = new WebSocket.Server({ port: 8080 });

        wsServer.on('connection', (ws) => {
            console.log('客户端连接成功');

            ws.on('message', async (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    // 只处理PDF打印请求
                    if (message.type === 'pdf') {
                        await handlePrintRequest(message);
                        ws.send(JSON.stringify({ status: 'success', message: 'PDF打印任务已处理' }));
                    } else {
                        ws.send(JSON.stringify({ status: 'error', message: '仅支持PDF打印' }));
                    }
                } catch (error) {
                    console.error('处理打印请求时出错:', error);
                    ws.send(JSON.stringify({ status: 'error', message: error.message }));
                }
            });

            ws.on('close', () => {
                console.log('客户端连接关闭');
            });
        });

        isServiceRunning = true;
        return { success: true, message: 'PDF打印服务启动成功，监听端口 8080' };
    } catch (error) {
        return { success: false, message: `服务启动失败: ${error.message}` };
    }
});

ipcMain.handle('stop-service', async () => {
    try {
        if (!isServiceRunning) {
            return { success: false, message: '服务未运行' };
        }

        if (wsServer) {
            wsServer.close();
            wsServer = null;
        }

        isServiceRunning = false;
        return { success: true, message: '服务已停止' };
    } catch (error) {
        return { success: false, message: `停止服务失败: ${error.message}` };
    }
});

ipcMain.handle('get-service-status', () => {
    return isServiceRunning;
});

// 新增：测试打印机功能
ipcMain.handle('test-printer', async () => {
    console.log('收到测试打印机请求');
    try {
        await printTestPage();
        return { success: true, message: '测试页已发送到默认打印机' };
    } catch (error) {
        return { success: false, message: `测试打印失败: ${error.message}` };
    }
});

// 新增获取默认打印机名字的 IPC 处理
ipcMain.handle('get-default-printer', async () => {
    try {
        const printer = await getDefaultPrinter();
        process.env.DEFAULT_PRINTER = printer.name;
        return printer.name;
    } catch (error) {
        console.error('获取默认打印机失败:', error);
        return '未知';
    }
});

// 处理PDF打印请求
async function handlePrintRequest(message) {
    const { data, filename } = message;
    await printPDF(data, filename);
}

// 打印PDF（保持不变）
async function printPDF(pdfBuffer, filename) {
    try {
        let buffer;
        try {
            buffer = Buffer.from(pdfBuffer, 'base64');
        } catch (error) {
            console.error('解析PDF数据失败:', error);
            throw new Error('PDF数据格式不正确');
        }

        const tempPdfPath = path.join(__dirname, `temp_${filename || 'document'}.pdf`);
        fs.writeFileSync(tempPdfPath, buffer);

        await print(tempPdfPath);

        // 延迟删除临时文件
        setTimeout(() => {
            if (fs.existsSync(tempPdfPath)) {
                fs.unlinkSync(tempPdfPath);
            }
        }, 3000);
    } catch (error) {
        console.error('打印PDF时出错:', error);
        throw error;
    }
}

// 新增：打印测试页功能
async function printTestPage() {
    return new Promise((resolve, reject) => {
        if (process.platform === 'win32') {
            // Windows：打印测试页
            const command = 'rundll32 printui.dll,PrintUIEntry /k /n "%DEFAULT_PRINTER%"';
            exec(command, (error, stdout, stderr) => {
                if (error) {
                    // 备用方法：使用PowerShell打印测试页
                    const backupCommand = 'powershell -Command "Get-WmiObject -Class Win32_Printer | Where-Object {$_.Default -eq $true} | ForEach-Object {$_.PrintTestPage()}"';
                    console.log(backupCommand);
                    exec(backupCommand, (backupError) => {
                        if (backupError) {
                            reject(new Error('无法打印测试页'));
                        } else {
                            resolve();
                        }
                    });
                } else {
                    resolve();
                }
            });
        } else if (process.platform === 'darwin') {
            // macOS：打印测试页
            const command = 'echo "打印机测试页\n$(date)\n系统信息: $(uname -a)" | lpr';
            exec(command, (error) => {
                if (error) {
                    reject(new Error('macOS测试页打印失败'));
                } else {
                    resolve();
                }
            });
        } else {
            // Linux：打印测试页
            const command = 'echo "打印机测试页\n$(date)\n系统信息: $(uname -a)" | lpr';
            exec(command, (error) => {
                if (error) {
                    reject(new Error('Linux测试页打印失败'));
                } else {
                    resolve();
                }
            });
        }
    });
}
